package com.guli.vod.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.*;
import com.guli.common.constants.ResultCodeEnum;
import com.guli.common.exception.GuliException;
import com.guli.vod.service.VideoService;
import com.guli.vod.util.AliyunVodSDKUtils;
import com.guli.vod.util.ConstantPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author XiaoHua666
 * @date 2019/4/28
 */
@Slf4j
@Service
public class VideoServiceImpl implements VideoService {
    @Override
    public String uploadVideo(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR);
        }

        UploadStreamRequest uploadStreamRequest = new UploadStreamRequest(
                ConstantPropertiesUtil.ACCESS_KEY_ID,
                ConstantPropertiesUtil.ACCESS_KEY_SECRET,
                title,
                fileName,
                inputStream
        );
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(uploadStreamRequest);

        String videoId = response.getVideoId();
        if (!response.isSuccess()) {
            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            if (StringUtils.isEmpty(videoId)) {
                throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
            }
        }
        return videoId;
    }

    @Override
    public void removeVideo(String videoId) {

        DefaultAcsClient client = null;
        try {
            client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);

            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);

            DeleteVideoResponse response = client.getAcsResponse(request);

        } catch (ClientException e) {
            throw new GuliException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }

    @Override
    public Boolean addtextWaterMark(String content) {
        DefaultAcsClient client = null;
        client = AliyunVodSDKUtils.initVodClient(
                ConstantPropertiesUtil.ACCESS_KEY_ID,
                ConstantPropertiesUtil.ACCESS_KEY_SECRET);

        AddWatermarkResponse response = new AddWatermarkResponse();
        try {
            //添加水印信息
            response = addWatermark(client, content);
            //水印ID
            System.out.println("WatermarkId = " + response.getWatermarkInfo().getWatermarkId());
            //水印的位置、效果配置数据
            System.out.println("WatermarkConfig = " + response.getWatermarkInfo().getWatermarkConfig());
            //水印文件的FileUrl(文字水印该字段值为空)
            System.out.println("FileUrl = " + response.getWatermarkInfo().getFileUrl());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ErrorMessage = " + e.getLocalizedMessage());
        }
        System.out.println("RequestId = " + response.getRequestId());
        return false;
    }

    @Override
    public CreateUploadVideoResponse getUploadAuthAndAddress(String title, String fileName) {
        try {
            //初始化
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //创建请求对象
            CreateUploadVideoRequest createUploadVideoRequest = new CreateUploadVideoRequest();
            createUploadVideoRequest.setTitle(title);
            createUploadVideoRequest.setFileName(fileName);
            JSONObject userData = new JSONObject();
            JSONObject messageCallback = new JSONObject();
            messageCallback.put("CallbackURL", "http://www.baidu.com");
            messageCallback.put("CallbackType", "http");
            userData.put("MessageCallback", messageCallback.toJSONString());
            JSONObject extend = new JSONObject();
            extend.put("MyId", "user-defined-id-11111");
            userData.put("Extend", extend.toJSONString());
            createUploadVideoRequest.setUserData(userData.toJSONString());

            CreateUploadVideoResponse response = client.getAcsResponse(createUploadVideoRequest);
            return response;
        } catch (ClientException e) {
            throw new GuliException(ResultCodeEnum.FETCH_VIDEO_PLAYAUTH_ERROR);
        }



    }

    @Override
    public RefreshUploadVideoResponse refreshUploadAuthAndAddress(String videoId) {
        try {

            //初始化
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //创建请求对象
            RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
            request.setVideoId(videoId);
            //获取响应
            RefreshUploadVideoResponse response = client.getAcsResponse(request);

            return response;

        } catch (ClientException e) {
            throw new GuliException(ResultCodeEnum.REFRESH_VIDEO_PLAYAUTH_ERROR);

        }
    }

    @Override
    public String getVideoPlayAuth(String videoId) {
        try {

            //初始化
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //请求
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoId);

            //获取响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            return  response.getPlayAuth();


        } catch (ClientException e) {
            throw new GuliException(ResultCodeEnum.REFRESH_VIDEO_PLAYAUTH_ERROR);

        }
    }

    /**
     * 添加水印配置信息函数
     */
    public static AddWatermarkResponse addWatermark(DefaultAcsClient client, String content) throws Exception {
        AddWatermarkRequest request = new AddWatermarkRequest();
        //水印名称
        request.setName("addwatermark");
        //获取水印文件在oss的URL
        // String fileUrl = "http://test-bucket.oss-cn-shanghai.aliyuncs.com/watermark/test.png";
        //图片水印必传图片文件的oss文件地址，水印文件必须和视频在同一个区域，例如:华东2视频，水印文件必须存放在华东2
        // request.setFileUrl(fileUrl);
        //水印配置数据
        JSONObject watermarkConfig = null;
        //图片水印的位置配置数据
        watermarkConfig = buildTextWatermarkConfig(content);
        //文字水印的位置配置数据
        //watermarkConfig = buildTextWatermarkConfig();
        request.setWatermarkConfig(watermarkConfig.toJSONString());
        //文字水印:Text; 图片水印:Image
        request.setType("Text");
        return client.getAcsResponse(request);
    }

    public static JSONObject buildTextWatermarkConfig(String content) {
        JSONObject watermarkConfig = new JSONObject();
        //文字水印显示的内容
        watermarkConfig.put("Content", content);
        //文字水印的字体名称
        watermarkConfig.put("FontName", "SimSun");
        //文字水印的字体大小
        watermarkConfig.put("FontSize", 25);
        //文字水印的颜色(也可为RGB颜色取值，例如:#000000)
        watermarkConfig.put("FontColor", "Black");
        //文字水印的透明度
        watermarkConfig.put("FontAlpha", "0.2");
        //文字水印的字体描边颜色(也可为RGB颜色取值，例如:#ffffff)
        watermarkConfig.put("BorderColor", "White");
        //文字水印的描边宽度
        watermarkConfig.put("BorderWidth", 1);
        //文字水印距离视频画面上边的偏移距离
        watermarkConfig.put("Top", 20);
        //文字水印距离视频画面左边的偏移距离
        watermarkConfig.put("Left", 15);
        return watermarkConfig;
    }


}
